package com.project.web.wechat.controller.app.webNative;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.project.common.core.utils.exception.CustomException;
import com.project.common.core.utils.exception.Result;
import com.project.common.core.utils.id.IDUtil;
import com.project.web.config.WxCorp.WxCpConfiguration;
import com.project.web.util.exception.WECHAT_RESP_CODE_ENUM;
import com.project.web.util.exception.WeChatCustomException;
import com.project.web.wechat.controller.common.BaseController;
import com.project.web.wechat.model.app.WxBizContactWay;
import com.project.web.wechat.service.app.WxBizContactWayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpExternalContactService;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.external.WxCpContactWayInfo;
import me.chanjar.weixin.cp.bean.external.WxCpContactWayResult;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 企业标签管理
 *
 * @Author: wyy
 * @Date: 4/8/21 4:49 PM
 */
@Api(tags = "【web】Crop Contact Way API")
@RestController("weChatServiceWxBizContactWayController")
@RequestMapping("/weChat/auth/web/contactWay")
public class WxBizContactWayController extends BaseController {

    /**
     * 日志工具类
     */
    public static final Logger log = LoggerFactory.getLogger(WxBizContactWayController.class);

    /**
     * 企业微信联系我业务接口
     */
    @Resource(name = "wxBizContactWayServiceImpl")
    private WxBizContactWayService wxBizContactWayService;

    /**
     * 客户联系列表【含分页】
     *
     * @param wxBizContactWay 联系我对象
     * @param pageNum         页码
     * @param pageSize        每页条数
     * @return
     */
    @ApiOperation(value = "客户联系列表【含分页】")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "pageNum", value = "页数", dataType = "Integer"),
            @ApiImplicitParam(paramType = "query", name = "pageSize", value = "每页多少", dataType = "Integer")
    })
    @GetMapping(value = "/selectListOfPage")
    public Result<PageInfo<WxBizContactWay>> selectListOfPage(WxBizContactWay wxBizContactWay, Integer pageNum, Integer pageSize) {
        if (pageNum == null || pageSize == null) {
            throw new WeChatCustomException(WECHAT_RESP_CODE_ENUM.MISS_PARAMETER);
        }
        PageHelper.startPage(pageNum, pageSize);
        List<WxBizContactWay> wxBizContactWays = wxBizContactWayService.selectList(wxBizContactWay);
        return getResult(new PageInfo(wxBizContactWays));
    }

    /**
     * 保存客户联系
     *
     * @param wxBizContactWay 企业标签
     * @return
     */
    @ApiOperation(value = "保存客户联系")
    @PostMapping(value = "/save")
    public Result<String> save(@RequestBody WxBizContactWay wxBizContactWay) {
        // 参数校验
        String userId = wxBizContactWay.getUserId();
        String state = wxBizContactWay.getState();
        if (StringUtils.isBlank(userId) || StringUtils.isBlank(state)) {
            throw new WeChatCustomException(WECHAT_RESP_CODE_ENUM.MISS_PARAMETER);
        }

        // 新增企业客户联系
        WxCpService wxCpService = WxCpConfiguration.getCpService("ww2dcc773582404eea", "110");
        WxCpExternalContactService contactService = wxCpService.getExternalContactService();
        String configId = "";
        String qrCode = "";
        String returnJson = "";
        try {
            // 添加企业微信标签到企业微信服务
            WxCpContactWayInfo wxCpContactWayInfo = new WxCpContactWayInfo();
            WxCpContactWayInfo.ContactWay contactWay = new WxCpContactWayInfo.ContactWay();
            contactWay.setType(WxCpContactWayInfo.TYPE.SINGLE);
            contactWay.setScene(WxCpContactWayInfo.SCENE.QRCODE);
            contactWay.setRemark("二维码方式");
            contactWay.setSkipVerify(true);
            contactWay.setState(wxBizContactWay.getState());
            // 设置成员
            List<String> users = new ArrayList<>();
            users.add(userId);
            contactWay.setUsers(users);
            wxCpContactWayInfo.setContactWay(contactWay);
            WxCpContactWayResult wxCpContactWayResult = contactService.addContactWay(wxCpContactWayInfo);
            configId = wxCpContactWayResult.getConfigId();
            qrCode = wxCpContactWayResult.getQrCode();
            returnJson = wxCpContactWayResult.toString();
        } catch (WxErrorException e) {
            log.error("添加企业客户标签出错：{}", ExceptionUtils.getStackTrace(e));
            throw new CustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }

        // 初始化参数
        wxBizContactWay.setId(IDUtil.getId());
        wxBizContactWay.setConfigId(configId);
        wxBizContactWay.setType(1);
        wxBizContactWay.setScene(2);
        wxBizContactWay.setRemark(wxBizContactWay.getTagName());
        wxBizContactWay.setSkipVerify(true);
        wxBizContactWay.setQrCode(qrCode);
        wxBizContactWay.setCreateDate(new Date());
        wxBizContactWayService.save(wxBizContactWay);
        return getResult(returnJson);
    }


}
